//
//  HDImageBrowserViewController.swift
//  HuaDaoPeifu
//
//  Created by Erickson on 16/5/11.
//  Copyright © 2016年 paiyipai. All rights reserved.
//

import UIKit
import SDWebImage
import SVProgressHUD
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
  switch (lhs, rhs) {
  case let (l?, r?):
    return l < r
  case (nil, _?):
    return true
  default:
    return false
  }
}

// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
  switch (lhs, rhs) {
  case let (l?, r?):
    return l > r
  default:
    return rhs < lhs
  }
}

// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func <= <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
  switch (lhs, rhs) {
  case let (l?, r?):
    return l <= r
  default:
    return !(rhs < lhs)
  }
}


protocol HDImageBrowserViewControllerDelegate :NSObjectProtocol{
    func didFinishedRetakePhoto(_ imageDetail:HDUploadDetailImageModel)
}


let placeHorderWH:CGFloat = 93
class HDImageBrowserViewController: UIViewController {

    var imageDetail : HDUploadDetailImageModel?
    weak var delegate:HDImageBrowserViewControllerDelegate?
    let scrollView = UIScrollView()
    var rightButtonItem:UIBarButtonItem!
    var currentScrollIndex = 0
    var lastScrollIndex = 0
    var allImageViews : [UIImageView] = []
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white
        setupViews()
        setupContentView()
        refreshRightItemTitle()
        loadImageOfCurrentImageView((imageDetail?.currentIndex)!)
    }
    
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        SVProgressHUD.dismiss()
    }
    
    func refreshRect(_ index:Int) -> CGRect{
        var currentRect = CGRect.zero
        let imgView = allImageViews[index]
        var rectH : CGFloat = 0
        if let image = imgView.image {
            rectH = image.size.height * AppConstant.screenWidth / image.size.width
        }
        if rectH < scrollView.bounds.size.height {
            currentRect = CGRect(x: CGFloat(index) * AppConstant.screenWidth, y: (scrollView.bounds.size.height - rectH)*0.5, width: AppConstant.screenWidth, height: rectH)
        } else {
            currentRect = CGRect(x: CGFloat(index) * AppConstant.screenWidth, y: 0, width: AppConstant.screenWidth, height: rectH)
        }
        
        return currentRect
    }
    
    func loadImageOfCurrentImageView(_ currentIndex:Int) {
        let currentImageView = allImageViews[currentIndex]
        let model = imageDetail!.uploadImags[currentIndex]
        if model.img == nil {
            let rect = refreshRect(currentIndex)

            currentImageView.image = model.notUploadImage
            currentImageView.frame = rect
            debugPrint("有图。。。")
        } else {
            debugPrint("无图，下载中")
            
            SVProgressHUD.showStatusWithLoading(nil)
            currentImageView.sd_setImage(with: URL(string: model.img), placeholderImage: UIImage(named: "大图"),options: .retryFailed, completed:{ (image, error, cacheType, url) in
                debugPrint("下载完成")
                DispatchQueue.main.async(execute: {

                    model.notUploadImage = image
                    currentImageView.image = model.notUploadImage
                    SVProgressHUD.dismiss()
                    let rect = self.refreshRect(currentIndex)
                    currentImageView.frame = rect


                })
                
            })
        }
    }
    
    func refreshRightItemTitle() {
        title = "\(currentScrollIndex + 1)/\(imageDetail!.uploadImags.count)"
        rightButtonItem = nil
        let currentStatus = imageDetail?.status as! Int
        switch currentStatus {
        case -1,0:
            let imgStatus = imageDetail!.uploadImags[currentScrollIndex].imageStatus

            imageStatusHandle(imgStatus)
            
            let caseModel = imageDetail?.uploadImags[currentScrollIndex]
            print(caseModel?.img)
            if caseModel?.img != nil{
                if caseModel?.img.characters.count > 0 {
                    rightButtonItem = nil
                }
            }
            
        case 2,5:
            if imageDetail!.IndexOfNewImage <= currentScrollIndex {
                let imgStatus = imageDetail!.uploadImags[currentScrollIndex].imageStatus
                imageStatusHandle(imgStatus)
            } else {
                rightButtonItem = nil
            }
        default:
            rightButtonItem = nil
        }
        navigationItem.rightBarButtonItem = rightButtonItem
        //0未提交 1审核中(速赔宝) 2有问题(初审) 3预结案 4已结案 5有问题（理审） 6审核中（华道）

    }
    func imageStatusHandle(_ imageStatus:HDImageStatus) {
        if imageStatus == .clear {
            rightButtonItem = UIBarButtonItem(title: "删除", style: .plain, target: self, action: #selector(HDImageBrowserViewController.deleCurrentImage))
        } else {
            rightButtonItem = UIBarButtonItem(title: "重拍", style: .plain, target: self, action: #selector(HDImageBrowserViewController.reTakePhoto(_:)))
        }
        
    }
    
    func deleCurrentImage() {
        
        let alertController = UIAlertController(title: "你确定删除吗？", message: nil, preferredStyle: .alert)
        
        let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        
        let certainAction = UIAlertAction(title: "确定", style: .default) { (certainAction) in
            self.deleteCurrentImage()
            //删除图片
        }
        alertController.addAction(certainAction)
        alertController.addAction(cancelAction)
        
        UIApplication.shared.keyWindow?.rootViewController!.present(alertController, animated: true, completion: nil)
    }
    
    func deleteCurrentImage() {
        
        if imageDetail?.uploadImags.count <= 1 {
            //popTo
            imageDetail?.uploadImags.removeAll()
            finishedImageDetailhandle()
            navigationController?.popViewController(animated: true)
            
        } else {
            if currentScrollIndex == 0 {
                scrollView.setContentOffset(CGPoint(x: scrollView.bounds.size.width, y: 0), animated: true)
                lastScrollIndex = 0
                
            } else {
                lastScrollIndex = currentScrollIndex - 1
                scrollView.setContentOffset(CGPoint(x: CGFloat(lastScrollIndex) *  scrollView.bounds.size.width, y: 0), animated: true)
            }
        }
        
        
        
    }
    
    func refresh() {
        
        imageDetail?.uploadImags.remove(at: currentScrollIndex)
        for subview in scrollView.subviews {
            subview.removeFromSuperview()
        }
        
        setupContentView()
        scrollView.setContentOffset(CGPoint(x: CGFloat(lastScrollIndex) * scrollView.bounds.size.width , y: 0), animated: false)
        currentScrollIndex = lastScrollIndex
        finishedImageDetailhandle()
    }
    
    func setupViews() {
        scrollView.isPagingEnabled = true
        scrollView.delegate = self
        view.addSubview(scrollView)
        scrollView.frame = CGRect(x: 0, y: 0, width: AppConstant.screenWidth, height: view.bounds.size.height - 64)

    }
    
    func reTakePhoto(_ sender:UIBarButtonItem) {
        deleteCurrentImage()
        let contr = HDTakePhotoViewController()
        contr.takeType = .retake
        contr.delegate = self
        let nav = BaseNavigationController(rootViewController: contr)
        
        
        UIApplication.shared.keyWindow?.rootViewController!.present(nav, animated: true, completion: {
            
        })

    }
    
    func setupContentView() {
        
        allImageViews.removeAll()
        let imageCount = imageDetail!.uploadImags.count
        
        for index in 0..<imageCount {
            
            let imgView = UIImageView()
            imgView.contentMode = .scaleAspectFill;
            imgView.tag = index
            var currentRect = CGRect.zero
            imgView.image = UIImage(named: "大图")
            currentRect = CGRect(x: (AppConstant.screenWidth-placeHorderWH)/2 + CGFloat(index) * AppConstant.screenWidth, y: (AppConstant.screenHeight - 64 - placeHorderWH)/2, width: placeHorderWH, height: placeHorderWH)
        
            imgView.frame = currentRect
            scrollView.addSubview(imgView)
            allImageViews.append(imgView)
            
        }

        scrollView.contentSize = CGSize(width: CGFloat(imageCount) * AppConstant.screenWidth, height: 0)
        
        scrollView.contentOffset = CGPoint(x: CGFloat(imageDetail!.currentIndex!) * AppConstant.screenWidth, y: 0)
        currentScrollIndex = imageDetail!.currentIndex!
        title = "\(currentScrollIndex + 1)/\(imageDetail!.uploadImags.count)"
    }
    
    
    func finishedImageDetailhandle() {
        delegate?.didFinishedRetakePhoto(imageDetail!)
    }
    
}

extension HDImageBrowserViewController : UIScrollViewDelegate {
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        let index = scrollView.contentOffset.x / AppConstant.screenWidth
        currentScrollIndex = Int(index)
        loadImageOfCurrentImageView(currentScrollIndex)
        refreshRightItemTitle()
    }
    
    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        refresh()
        loadImageOfCurrentImageView(currentScrollIndex)
        refreshRightItemTitle()
    }
}

extension HDImageBrowserViewController: HDTakePhotoViewControllerDelegate {
    func numberOfPhotosNeedToUpload() -> Int {
        if imageDetail!.IndexOfNewImage < imageDetail!.uploadImags.count - 1 {
            print(imageDetail?.uploadImags.count)
            print(imageDetail!.IndexOfNewImage!)
            let count = (imageDetail?.uploadImags.count)! - imageDetail!.IndexOfNewImage!
            return 10 - count
        }
        return (imageDetail?.uploadImags.count)!
    }
    
    func didFinishedPickPhotos(_ images: [HDUploadImageModel]) {
        

    }
    
    func didRetakePhoto() {
        navigationController?.popViewController(animated: true)
    }
    func didFinishedTakePhotos(_ image: [HDPayoutCaseInitModel]) {
        
        imageDetail?.uploadImags.insert(contentsOf: image, at: currentScrollIndex)
        finishedImageDetailhandle()
        navigationController?.popViewController(animated: false)

    }
}

